const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // html 模版和压缩html
const { ProvidePlugin } = require('webpack'); // 垫片
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); // 提取css
const { merge } = require('webpack-merge'); //合并配置
const devConfig = require('./dev');
const proConfig = require('./prod');
const SpeedMeasureWebpackPlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasureWebpackPlugin();
let config = isPro => {
  return {
    entry: './src/index.js',
    output: {
      filename: 'js/[name]_bundle.js',
      path: path.resolve(__dirname, '../build'),
      clean: true,
      chunkFilename: 'js/[name]_chunk.js'
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude:/node_modules/,
          use: [
            {
              loader: 'babel-loader'
            }
          ]
        },
        {
          test: /\.ts$/i,
          //use:'ts-loader'
          exclude:/node_modules/,
          use: ['babel-loader']
        },
        {
          test: /\.css$/,
          use: [
            isPro ? MiniCssExtractPlugin.loader : 'style-loader',
            'css-loader'
          ]
        }
      ]
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: './index.html',
        minify: {
          // 针对 html模版进行压缩
          collapseWhitespace: true,
          keepClosingSlash: true,
          removeComments: true,
          removeRedundantAttributes: true,
          removeScriptTypeAttributes: true,
          removeStyleLinkTypeAttributes: true,
          useShortDoctype: true
        }
      }),
      new ProvidePlugin({
        axios: ['axios', 'default'],
        get: ['axios', 'default', 'get']
      })
    ]
  };
};

module.exports = env => {
  const isProd = env.production;
  return smp.wrap(merge(config(isProd), isProd ? proConfig : devConfig));
};
